package com.atguigu.gulimall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.common.utils.HttpUtils;
import com.atguigu.gulimall.member.dao.MemberLevelDao;
import com.atguigu.gulimall.member.entity.MemberLevelEntity;
import com.atguigu.gulimall.member.exception.PhoneExistException;
import com.atguigu.gulimall.member.exception.UsernameExistException;
import com.atguigu.gulimall.member.vo.MemberRegistVo;
import com.atguigu.gulimall.member.vo.MemerLoginVo;
import com.atguigu.gulimall.member.vo.SocialUser;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.member.dao.MemberDao;
import com.atguigu.gulimall.member.entity.MemberEntity;
import com.atguigu.gulimall.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {


    @Autowired
    private MemberLevelDao memberLevelDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void regist(MemberRegistVo vo) {

        MemberDao memberDao = this.baseMapper;
        MemberEntity entity = new MemberEntity();
        //设置默认等级
        MemberLevelEntity levelEntity = memberLevelDao.getDefaultLevlel();
        entity.setLevelId(levelEntity.getId());

        /**
         * 检查用户名和手机号是否唯一,因为是void没有返回值，为了让controller能感知异常，异常机制
         */
        checkPhoneUnique(vo.getPhone());
        checkUsernameUnique(vo.getUserName());

        entity.setMobile(vo.getPhone());
        entity.setUsername(vo.getUserName());
        entity.setNickname(vo.getUserName());
        //密码要进行加密存储   MD5&盐值&BCrypt
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(vo.getPassword());
        entity.setPassword(encode);
        //其他的默认信息

        //保存
        memberDao.insert(entity);
    }

    @Override
    public void checkPhoneUnique(String phone) throws PhoneExistException{
        MemberDao memberDao = this.baseMapper;
        Integer mobile = memberDao.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if(mobile>0){
            throw new PhoneExistException();
        }
    }


    @Override
    public void checkUsernameUnique(String username) throws UsernameExistException{
        MemberDao memberDao = this.baseMapper;
        Integer count = memberDao.selectCount(new QueryWrapper<MemberEntity>().eq("username", username));
        if(count>0){
            throw new UsernameExistException();
        }
    }

    @Override
    public MemberEntity login(MemerLoginVo vo) {


        //1、去数据库查询
        MemberDao memberDao = this.baseMapper;
        MemberEntity entity = memberDao.selectOne(new QueryWrapper<MemberEntity>()
                .eq("username", vo.getLoginacct())
                .or()
                .eq("mobile", vo.getPassword()));
         if(entity==null){
             //登录失败
             return null;
         }
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
         //密码匹配前端的密码  和 数据库的密码匹配
        boolean matches = passwordEncoder.matches(vo.getPassword(), entity.getPassword());
        if(matches){
            return entity;
        }
        return null;
    }



    @Override
    public MemberEntity oauthlogin(SocialUser vo) throws Exception {
          //登录和注册合并逻辑
        String uid = vo.getUid();
        //1、判断当前社交用户是否已经登录过系统；
        MemberDao memberDao = this.baseMapper;
        MemberEntity memberEntity = memberDao.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));
        if(memberEntity != null ){
            //这个用户已经 注册
            MemberEntity update = new MemberEntity();
            update.setId(memberEntity.getId());
            update.setAccessToken(vo.getAccess_token());
            update.setExpiresIn(vo.getExpires_in());
            memberDao.updateById(update);


            memberEntity.setAccessToken(vo.getAccess_token());
            memberEntity.setExpiresIn(vo.getExpires_in());
            return memberEntity;
        }else{
            //2、没有查询到，就需要注册一个
            MemberEntity regist = new MemberEntity();
            //3、查出当前社交用的社交账号信息（昵称，性别等）
            HashMap<String,String> query = new HashMap<>();
            query.put("access_token",vo.getAccess_token());
            query.put("uid",vo.getUid());
            HttpResponse response = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "get", new HashMap<String, String>(), query);
            if(response.getStatusLine().getStatusCode() == 200){
               try{
                  //查询成功
                  String json = EntityUtils.toString(response.getEntity());
                  JSONObject object = JSON.parseObject(json);
                  //昵称
                  String name = object.getString("name");
                  String gander = object.getString("gander");
                  //.....

                  regist.setNickname(name);
                  regist.setGender("m".equals(gander)?1:0);
                  //.....
               }catch (Exception e){

               }
            }
            regist.setSocialUid(vo.getUid());//
            regist.setAccessToken(vo.getAccess_token());//token
            regist.setExpiresIn(vo.getExpires_in());//过期时间
            memberDao.insert(regist);

            return regist;
        }
    }

}